package br.com.sgac.controler;

import java.io.IOException;
import java.util.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.jni.Mmap;

import br.com.sgac.dao.MedicamentoDAO;
import br.com.sgac.model.Medicamento;

public class MedicamentoServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	
	MedicamentoDAO medicamentoDAO = new MedicamentoDAO();
	
	public MedicamentoServlet() {
		super();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Medicamento> medicamentos = new ArrayList<Medicamento>();
		Medicamento medicamento = new Medicamento();
		
		String editar = request.getParameter("editar");
		medicamentos = medicamentoDAO.findAll();
		request.setAttribute("medicamentos", medicamentos);
		
		if(editar != null) {
			medicamento = medicamentoDAO.findMedicamentoById(editar);
			request.setAttribute("medicamento", medicamento);
			RequestDispatcher rd = request.getRequestDispatcher("app/FormEditMedicamento.jsp");
			rd.forward(request, response);
		}else{
			RequestDispatcher rd = request.getRequestDispatcher("app/FormCadMedicamento.jsp");
			rd.forward(request, response);
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Medicamento medicamento = new Medicamento();
		
		String nome = request.getParameter("nomeMedicamento");
		String descricao = request.getParameter("descricaoMedicamento");
		
		medicamento.setNomeMedicamento(nome);
		medicamento.setDescricaoMedicamento(descricao);
		
		medicamentoDAO.begin();
		medicamentoDAO.merge(medicamento);
		medicamentoDAO.commit();
		medicamentoDAO.close();
	}
}
